import react, { JSX, useEffect } from 'react'
import EventEmitter from '../EventEmitter'
import styles from './style.module.scss'
type MessageBoxEvent = {
  showMessageBox: (props: MessageBoxProps) => void
}
enum MessageBoxType {
  info,
  warn,
  propt,
}
type ContentType = string | (() => JSX.Element)
interface MessageBoxProps {
  type: MessageBoxType
  title: string
  text: ContentType
  confirmText?: string
  cancelText?: string
  resolve?: (value: boolean) => void
}

const emit = new EventEmitter<MessageBoxEvent>()
let isUseMessageBox = false

export function useMessageBox() {
  const MessageBox = () => {
    const [messageBoxList, setMessageBoxList] = react.useState<
      MessageBoxProps[]
    >([])

    useEffect(() => {
      const uninstall = emit.on('showMessageBox', (props) => {
        setMessageBoxList((list) => {
          return [...list, props]
        })
      })
      if (isUseMessageBox) {
        console.error('无需使用多个Toast挂载')
      }
      isUseMessageBox = true
      return () => {
        isUseMessageBox = false
        uninstall()
      }
    }, [])
    function onConfirmHandler(index: number) {
      // console.log(messageBoxList)
      messageBoxList[index].resolve(true)
      setMessageBoxList((list) => {
        list.splice(index, 1)
        return [...list]
      })
    }
    function onCancelHandler(index: number) {
      messageBoxList[index].resolve(false)
      setMessageBoxList((list) => {
        list.splice(index, 1)
        return [...list]
      })
    }
    useEffect(() => {
      if (messageBoxList.length == 0) {
        return
      }
      const onKeyUp = (e: KeyboardEvent) => {
        if (e.key === 'Enter') {
          onConfirmHandler(messageBoxList.length - 1)
        } else if (e.key == 'Escape') {
          onCancelHandler(messageBoxList.length - 1)
        }
      }
      window.addEventListener('keyup', onKeyUp)
      return () => {
        window.removeEventListener('keyup', onKeyUp)
      }
    }, [messageBoxList])

    return (
      <div>
        {messageBoxList.map((item, index) => {
          return (
            <div className={styles['box-message-box-view']} key={index}>
              <div className={styles['box-message-box-mask']}></div>
              <div
                className={styles['box-message-box']}
                style={{
                  width:
                    typeof item.text == 'string' && item.text.length > 150
                      ? '800px'
                      : '500px',
                }}>
                <div className={styles['top-view']}>
                  <div className={styles['title']}>{item.title}</div>
                  <div
                    className={styles['close']}
                    onClick={() => onCancelHandler(index)}>
                    <svg
                      viewBox="0 0 1024 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      p-id="3343"
                      width="200"
                      height="200">
                      <path
                        d="M556.8 512L832 236.8c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0L512 467.2l-275.2-277.333333c-12.8-12.8-32-12.8-44.8 0-12.8 12.8-12.8 32 0 44.8l275.2 277.333333-277.333333 275.2c-12.8 12.8-12.8 32 0 44.8 6.4 6.4 14.933333 8.533333 23.466666 8.533333s17.066667-2.133333 23.466667-8.533333L512 556.8 787.2 832c6.4 6.4 14.933333 8.533333 23.466667 8.533333s17.066667-2.133333 23.466666-8.533333c12.8-12.8 12.8-32 0-44.8L556.8 512z"
                        p-id="3344"></path>
                    </svg>
                  </div>
                </div>
                <div className={styles['content-view']}>
                  {typeof item.text == 'string' && item.text}
                  {typeof item.text != 'string' && <item.text />}
                </div>
                <div className={styles['bottom-view']}>
                  {item.type === MessageBoxType.propt && (
                    <div
                      className={styles['cancel']}
                      onClick={() => onCancelHandler(index)}>
                      {item.cancelText || '取消'}
                    </div>
                  )}
                  <div
                    className={styles['confirm']}
                    onClick={() => onConfirmHandler(index)}>
                    {item.confirmText || '确定'}
                  </div>
                </div>
              </div>
            </div>
          )
        })}
      </div>
    )
  }
  return { MessageBox }
}
function showMessageBox(props: MessageBoxProps) {
  if (!isUseMessageBox) {
    console.error('请先使用useMessageBox挂载')
    return
  }
  let resolve = null as ((value: boolean) => void) | null
  const promise = new Promise<boolean>((r) => (resolve = r))
  emit.emit('showMessageBox', {
    type: props.type,
    title: props.title,
    text: props.text,
    cancelText: props.cancelText,
    confirmText: props.confirmText,
    resolve: resolve!,
  })
  return promise
}

interface PropMoreOption {
  cancelText?: string
  confirmText?: string
}
export const MessageBox = {
  info: (title: string, text: ContentType) =>
    showMessageBox({ title, text, type: MessageBoxType.info }),
  warn: (title: string, text: ContentType) =>
    showMessageBox({ title, text, type: MessageBoxType.warn }),
  propt: (title: string, text: ContentType, option: PropMoreOption = {}) => {
    return showMessageBox({
      title,
      text,
      type: MessageBoxType.propt,
      cancelText: option.cancelText,
      confirmText: option.confirmText,
    })
  },
}
